package com.tdzh.maimaiti.view;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tdzh.maimaiti.R;
import com.tdzh.maimaiti.biz.GetContractList;
import com.tdzh.maimaiti.util.UriAPI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MyFriendsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MyFriendsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyFriendsFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ImageView mIconFriendApp;
    private TextView mFriendApp;
    private ListView mFriendsList;
    private LinearLayout mAppLayout;
    private ImageView mSearchContract;

    private String userphone;
    private AsyncTask mGetFriends;

    private OnFragmentInteractionListener mListener;

    public MyFriendsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyFriendsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyFriendsFragment newInstance(String param1, String param2) {
        MyFriendsFragment fragment = new MyFriendsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        SharedPreferences user = getActivity().getSharedPreferences("account", 0);
        userphone = user.getString("name", null);

        View view =  inflater.inflate(R.layout.fragment_my_friends, container, false);
        mIconFriendApp = (ImageView) view.findViewById(R.id.imageViewFriendApp);
        mFriendApp = (TextView) view.findViewById(R.id.friendApp);
        mFriendsList = (ListView) view.findViewById(R.id.friendsList);
        mAppLayout = (LinearLayout) view.findViewById(R.id.appLayout);
        mSearchContract = (ImageView) view.findViewById(R.id.imageViewSearchContract);

        mAppLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FriendsAppActivity.class);
                startActivity(intent);

            }
        });

        mSearchContract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ContractListActivity.class);
                startActivity(intent);
            }
        });

        mGetFriends = new GetFriendsTask(userphone, UriAPI.HTTPFriends);
        mGetFriends.execute((Void)null);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
   /* public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }*/

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public class GetFriendsTask extends AsyncTask {

        private final String mPhone;
        private final String mUrl;

        GetFriendsTask(String userPhone,String url) {
            mPhone = userPhone;
            mUrl = url;
        }

        @Override
        protected Object doInBackground(Object... params) {
            String result = "";
            //ArrayList list = params;
            //请求数据
            HttpPost httpRequest = new HttpPost(mUrl);
            byte[] data = new byte[2048];
          //  System.out.println(mPhone);
            try {
                //创建参数

                //JSONArray jsonArray = new JSONArray(( (  (ArrayList<Map<String,Object>>) params[0]).toString()));
                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                nameValuePair.add(new BasicNameValuePair("ContractList", "13269338058"));
                System.out.println("已启动 ");
                //对提交数据进行编码
                httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair
                        , HTTP.UTF_8));
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                //获取响应服务器的数据
                System.out.println("连接 " + httpResponse.getStatusLine().getStatusCode());
                if (httpResponse.getStatusLine().getStatusCode() == 200) {

                    //先把从服务端来的数据转化成字节数组
                    data = EntityUtils.toByteArray((HttpEntity) httpResponse.getEntity());
                    //再创建字节数组输入流对象
                    ByteArrayInputStream bais = new ByteArrayInputStream(data);
                    //绑定字节流和数据包装流
                    DataInputStream dis = new DataInputStream(bais);
                    //将字节数组中的数据还原成原来的各种数据类型，代码如下：
                    result = new String(dis.readUTF());
                    //inStream.close();
                    System.out.println("result 第二次" + result);
                    //Log.i("服务器返回信息:", result);
                    //return data;
                    //

                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Object result) {
            mGetFriends = null;
            List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
            String r = result.toString();
            try {
                list2 = GetContractList.resolveContractsList(r);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            if (list2 != null) {
                System.out.println("result " + r);

                SimpleAdapter adapter = new SimpleAdapter(getContext(), list2, R.layout.friend_item,
                        new String[]{"name", "phoneNumber", "image"},
                        new int[]{R.id.friendName, R.id.friendPhonenumber, R.id.friendIcon});
                mFriendsList.setAdapter(adapter);

            } else{

                Toast.makeText(getContext(), "获取失败", Toast.LENGTH_SHORT);
                //Intent intent = new Intent(MyP,);

            }
        }

    }


}
